package org.lgiavedoni.android.franq.core.communication.imp.phone;

import org.lgiavedoni.android.franq.core.communication.CommunicationSource;
import org.lgiavedoni.android.franq.core.message.MessageOut;
import org.lgiavedoni.android.franq.service.phone.ContextService;
import org.lgiavedoni.android.franq.util.LoopUtil;
import org.lgiavedoni.android.franq.util.phone.PhoneUtil;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.widget.RemoteViews;
import android.widget.Toast;

public class CommunicationPhone implements CommunicationSource {

	public static final CommunicationPhone inst = new CommunicationPhone();

	private int layoutId = -1;
	private int viewId = -1;
	private Class<? extends AppWidgetProvider> activity;
	private AppWidgetManager manager;

	private CommunicationPhone() {
	}

	public void sendMessage(MessageOut message) {
		LoopUtil.prepare();

		if (ContextService.inst.getApplicationContext() != null) {
			Toast.makeText(ContextService.inst.getApplicationContext(), message.getText(), Toast.LENGTH_LONG).show();
		}
		if (viewId != -1) {
			/*
			 * view.setTextViewText(viewId, message.getText());
			 * getManger().updateAppWidget(viewId, view);
			 */
			ComponentName me = new ComponentName(ContextService.inst.getApplicationContext(), activity);
			RemoteViews updateViews = new RemoteViews(ContextService.inst.getApplicationContext().getPackageName(), layoutId);
			updateViews.setTextViewText(viewId, message.getText());

			AppWidgetManager mgr = AppWidgetManager.getInstance(ContextService.inst.getApplicationContext());

			mgr.updateAppWidget(me, updateViews);
		}
		// Vibrate
		PhoneUtil.vibrateDefault();
	}

	public void setView(int layoutId, int viewId, Class<? extends AppWidgetProvider> activity) {
		this.layoutId = layoutId;
		this.viewId = viewId;
		this.activity = activity;
	}

	private AppWidgetManager getManger() {
		if (manager != null)
			return manager;
		if (ContextService.inst.getApplicationContext() != null) {
			manager = AppWidgetManager.getInstance(ContextService.inst.getApplicationContext());
		}
		return manager;
	}

}
